package club.xyes.zkh.ecommerce.service.listener.impl;

import club.xyes.zkh.ecommerce.commons.context.ApplicationConstants;
import club.xyes.zkh.ecommerce.commons.entity.Coupon;
import club.xyes.zkh.ecommerce.commons.entity.Shop;
import club.xyes.zkh.ecommerce.commons.entity.User;
import club.xyes.zkh.ecommerce.commons.entity.WxFormId;
import club.xyes.zkh.ecommerce.commons.properties.WechatConfigurationProperties;
import club.xyes.zkh.ecommerce.commons.util.CouponUtils;
import club.xyes.zkh.ecommerce.commons.util.DateTimeUtil;
import club.xyes.zkh.ecommerce.service.WxFormIdService;
import club.xyes.zkh.ecommerce.service.listener.OnCouponGrantListener;
import club.xyes.zkh.ecommerce.wechat.dto.SendTemplateMsgResult;
import club.xyes.zkh.ecommerce.wechat.dto.TemplateMsgData;
import club.xyes.zkh.ecommerce.wechat.dto.WxAccessToken;
import club.xyes.zkh.ecommerce.wechat.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Create by 郭文梁 2019/5/16 0016 13:31
 * OnCouponGrantListenerImpl
 * 优惠券发放监听器实现
 *
 * @author 郭文梁
 * @data 2019/5/16 0016
 */
@Component
@Slf4j
public class OnCouponGrantListenerImpl implements OnCouponGrantListener {
    /**
     * 优惠券通知模板消息ID
     */
    private static final String COUPON_GRANT_TEMPLATE_MSG_ID = "4nC6LLaeGyu-V5-gm2-0HIR-h38MHf2YPUhglwON52M";
    private final WeChatService weChatService;
    private final WechatConfigurationProperties wechatConfigurationProperties;
    private final WxFormIdService wxFormIdService;

    @Autowired
    public OnCouponGrantListenerImpl(WeChatService weChatService,
                                     WechatConfigurationProperties wechatConfigurationProperties,
                                     WxFormIdService wxFormIdService) {
        this.weChatService = weChatService;
        this.wechatConfigurationProperties = wechatConfigurationProperties;
        this.wxFormIdService = wxFormIdService;
    }

    @Override
    public void onGrant(User user, Coupon coupon, Shop shop) {
        String appId = wechatConfigurationProperties.getUserMicroProgramAppId();
        String secret = wechatConfigurationProperties.getUserMicroProgramSecret();
        WxFormId formId = wxFormIdService.popOne(appId, user.getWxOpenId());
        if (formId == null) {
            log.info("Could not send TemplateMsg, there id no available formId,[{},{}]", appId, user.getWxOpenId());
            return;
        }

        Map<String, TemplateMsgData> data = buildTemplateMsgData(user, coupon, shop);
        Map<String, String> miniProgram = new HashMap<>(2);
        miniProgram.put("pagepath", "pages/coupon/coupon");
        Map<String, Object> options = new HashMap<>(10);
        options.put("page", "pages/coupon/coupon");
        try {
            WxAccessToken token = weChatService.getAccessToken(appId, secret);
            SendTemplateMsgResult sendResult = weChatService.sendTemplateMsg(appId,
                    token,
                    formId.getFormId(),
                    COUPON_GRANT_TEMPLATE_MSG_ID,
                    user.getWxOpenId(), data, miniProgram, options);
            log.info("TemplateMsg send Result {}", sendResult);
        } catch (IOException e) {
            log.info("Send template msg fail", e);
        }
    }

    /**
     * 构建模板消息参数
     *
     * @param coupon 优惠券
     * @param shop   商家
     * @return 参数
     */
    private Map<String, TemplateMsgData> buildTemplateMsgData(User user, Coupon coupon, Shop shop) {
        String date = DateTimeUtil.format(DateTimeUtil.now(), ApplicationConstants.DATE_TIME_FORMAT);
        Map<String, TemplateMsgData> data = new HashMap<>(4);
        data.put("keyword1", new TemplateMsgData(user.getName()));
        data.put("keyword2", new TemplateMsgData(shop.getName()));
        data.put("keyword3", new TemplateMsgData("商家发放"));
        data.put("keyword4", new TemplateMsgData("优惠券：" + coupon.getName()));
        data.put("keyword5", new TemplateMsgData(CouponUtils.toDescription(coupon)));
        data.put("keyword6", new TemplateMsgData(date));
        return data;
    }
}
